package com.tnf.bc.bground.datasource.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.tnf.bc.bground.datasource.properties.DataSourceParame;
import com.tnf.bc.bground.datasource.properties.DynamicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: //数据源配置类
 * @author: lzl
 * @create: 2022-11-18 12:10
 **/

@Configuration
public class DruidConfig {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean(name = "fantasyDataSource")
    @ConfigurationProperties("spring.datasource.fantasy")
    public DataSource fantasyDataSource(DataSourceProperties druidProperties) {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "romanticDataSource")
    @ConfigurationProperties("spring.datasource.romantic")
    @ConditionalOnProperty(prefix = "spring.datasource.romantic", name = "enabled", havingValue = "true")
    public DataSource romanticDataSource(DataSourceProperties druidProperties) {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource fantasyDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceParame.DSFANTASY_NAME, fantasyDataSource);
        DataSourceParame.DS_NAME_LIST.add(DataSourceParame.DSFANTASY_NAME);
        setDataSource(targetDataSources, DataSourceParame.DSROMANTIC_NAME, "romanticDataSource");
        return new DynamicDataSource(fantasyDataSource, targetDataSources);
    }

    /**
     * 设置数据源
     *
     * @param targetDataSources 备选数据源集合
     * @param sourceName        数据源名称
     * @param beanName          bean名称
     */
    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName) {
        try {
            DataSource dataSource = (DataSource)applicationContext.getBean(beanName);
            targetDataSources.put(sourceName, dataSource);
            DataSourceParame.DS_NAME_LIST.add(sourceName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
